package com.alogic.together2.xscript;

import com.alogic.together2.TogetherConstants;
import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.logicbus.backend.Context;
import org.apache.commons.lang3.StringUtils;

/**
 * 获取Http请求头
 *
 * @since 1.6.14.5 [20210413 duanyy] <br>
 */
public class GetHeader extends AbstractLogiclet implements TogetherConstants {

    protected String pid = ID_CONTEXT;

    protected String $id = "";
    protected String $header = "";
    protected String $dft = "";


    public GetHeader(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        pid = PropertiesConstants.getString(p,"pid",pid,true);
        $id = PropertiesConstants.getRaw(p,"id",$id);
        $header = PropertiesConstants.getRaw(p,"header",$header);
        $dft = PropertiesConstants.getRaw(p,"dft",$dft);
    }

    @Override
    protected void onExecute(final XsObject root, final XsObject current, final LogicletContext ctx, final ExecuteWatcher watcher){
        Context httpContext = ctx.getObject(pid);
        if (httpContext != null){
            String id = ctx.transform($id);
            if (StringUtils.isNotEmpty(id)){
                String name = PropertiesConstants.transform(ctx,$header,"");
                if (StringUtils.isNotEmpty(name)){
                    String data = httpContext.getRequestHeader(name);
                    if (StringUtils.isNotEmpty(data)){
                        ctx.SetValue(id,data);
                    }else{
                        ctx.SetValue(id,PropertiesConstants.transform(ctx,$dft,""));
                    }
                }else{
                    ctx.SetValue(id,PropertiesConstants.transform(ctx,$dft,""));
                }
            }
        }
    }
}